// 服务管理命令
use serde::{Deserialize, Serialize};
use tauri::command;

use crate::error::AppError;
use crate::services::manager::{get_service_manager, ServiceStatus};

/// 服务状态响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceStatusResponse {
    pub status: String,
    pub uptime_seconds: Option<u64>,
    pub services: ServiceDetails,
}

/// 服务详情
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceDetails {
    pub graph_system: bool,
}

/// 健康检查响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckResponse {
    pub healthy: bool,
    pub status: String,
    pub services: ServiceDetails,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// 获取服务状态
#[command]
pub async fn get_service_status() -> Result<ServiceStatusResponse, AppError> {
    let service_manager = get_service_manager();
    let status = service_manager.get_status().await;
    
    // 检查各个服务的状态
    let graph_system = service_manager.get_graph_system().read().await.is_some();

    let status_str = match status {
        ServiceStatus::Stopped => "stopped",
        ServiceStatus::Starting => "starting",
        ServiceStatus::Running => "running",
        ServiceStatus::Stopping => "stopping",
        ServiceStatus::Error(ref msg) => "error",
    }.to_string();

    Ok(ServiceStatusResponse {
        status: status_str,
        uptime_seconds: None, // TODO: 实现运行时间跟踪
        services: ServiceDetails {
            graph_system,
        },
    })
}

/// 重启服务
#[command]
pub async fn restart_services() -> Result<String, AppError> {
    let service_manager = get_service_manager();
    
    service_manager.restart().await?;
    
    Ok("Services restarted successfully".to_string())
}

/// 健康检查
#[command]
pub async fn health_check() -> Result<HealthCheckResponse, AppError> {
    let service_manager = get_service_manager();
    
    let healthy = service_manager.health_check().await?;
    let status = service_manager.get_status().await;
    
    // 检查各个服务的状态
    let graph_system = service_manager.get_graph_system().read().await.is_some();

    let status_str = match status {
        ServiceStatus::Stopped => "stopped",
        ServiceStatus::Starting => "starting",
        ServiceStatus::Running => "running",
        ServiceStatus::Stopping => "stopping",
        ServiceStatus::Error(ref msg) => "error",
    }.to_string();

    Ok(HealthCheckResponse {
        healthy,
        status: status_str,
        services: ServiceDetails {
            graph_system,
        },
        timestamp: chrono::Utc::now(),
    })
}
